package main

import (
	"fmt"
	"github.com/bitly/go-simplejson"
	"io"
	"net/http"
	"sync"
	"time"
	"webDownloader/engine/generic"
	_ "webDownloader/engine/netease"
	_ "webDownloader/engine/wx_article_catcher"
)

var currentVersion = 20231018

func checkUpdate() {
	versionMgr, err := http.Get("https://gitee.com/kbtxwer/kbtxwer/raw/master/version_center.json")
	if err == nil {
		versionInfo, _ := io.ReadAll(versionMgr.Body)
		json, _ := simplejson.NewJson(versionInfo)
		newVersion, _ := json.Get("wxac").Get("app_version").Int()
		if newVersion > currentVersion {
			fmt.Println("***********************")
			fmt.Println("当前有新版本发布！版本号", newVersion, "\n更新内容：")
			desc, _ := json.Get("wxac").Get("description").String()
			fmt.Println(desc)
			link, _ := json.Get("wxac").Get("link").String()
			fmt.Println("请访问", link, "下载更新")
			fmt.Print("***********************\n\n\n")
		} else {
			fmt.Println("当前已是最新版本！")
		}
	} else {
		fmt.Println("更新检查失败！错误信息：", err)
	}
}

func main() {

	// 检查更新
	checkUpdate()

	eng := generic.GetEngine()
	if !eng.Auth() {
		return
	}
	config := eng.ParseConfig()

	fmt.Println("当前配置：", *config)

	eng.ParseDownloadTask()
	tasks := eng.SyncDownloadTask()

	// 等待所有的 go routine 执行完毕再提示下载完成
	var wg sync.WaitGroup
	fmt.Printf("\n正在下载(%d / %d)", 0, len(tasks))
	for index, task := range tasks {
		wg.Add(1)
		go task.Download(&wg)
		fmt.Printf("\r正在下载(%d / %d)", index+1, len(tasks))
		time.Sleep(time.Millisecond * 100)
	}
	fmt.Println()
	wg.Wait()

	// 在这里显示下载完成的提示信息，或者捐助等
	eng.ShowEndMessage()
}
